<?php
namespace fast;

use think\Db;
use fast\Http;
use fast\RsaUtil;
use Exception;
class Huipaynew
{
    const merchantNo = '810083647187'; //请写入自己的APPID
    const privateKey = 'b3dbae94bfb7d4a8a01170e60d52bbcf'; //请写入自己的APPKEY
   
    const url = 'https://api-backup.huishouqian.com/api/acquiring'; //生产请求URL


    public static function addOrder($token,$transNo,$price,$returnUrl,$ip){

        $data['method'] = 'POLYMERIZE_MAIN_SWEPTN';
        $data['version'] = '1.0';
        $data['format'] = 'JSON';
        $data['merchantNo'] = self::merchantNo;
        $data['signType'] = 'RSA2';
        $data['signContent'] = '';
        $data['sign'] = '';

        $pay_data['transNo'] = $transNo;
        $pay_data['payType'] = 'WECHAT_APPLET';
        $pay_data['returnUrl'] = $returnUrl;
        $pay_data['orderAmt'] = bcmul($price, 100);
        $pay_data['goodsInfo'] = '冻宝云冻品';
        $pay_data['requestDate'] = date('YmdHis');
        $pay_data['memo'] = [];
        $pay_data['memo']['appid'] = 'wx80d5e749a136ffb3';
        $pay_data['memo']['openid'] = $token;
        $pay_data['memo']['description'] = '冻宝云冻品';
        $pay_data['memo']['spbillCreateIp'] = $ip;

        $data['signContent'] = json_encode($pay_data,JSON_UNESCAPED_UNICODE);
        
        
        
        logs('third_pay3',$data['signContent']);  
        
        
        $destDir = ROOT_PATH . 'public'. DS;

        $rsaUtil = new RsaUtil($destDir .'dongbaoyun_pri.pfx',$destDir .'MANDAO_810083647187_pub.cer','123456');

        $signStr = "method=".$data['method']."&version=".$data['version']."&format=".$data['format']."&merchantNo=".$data['merchantNo']."&signType=".$data['signType']."&signContent=".$data['signContent']."&key=".self::privateKey;



        // echo "[请求]固定格式拼接后明文：".$signStr."\r\n";
        $encrypted = $rsaUtil->sign($signStr);
        // echo "[请求]RSA加签后内容：", $encrypted."\r\n";

        $data['sign'] = $encrypted;



      

        // $headers = ['Content-type: application/json'];
        $headers = [];
        $options = [
            CURLOPT_HTTPHEADER => $headers
        ];

        // $data = json_encode($data,JSON_UNESCAPED_UNICODE);

        // var_dump($data);

        $response = Http::sendRequest(self::url, $data, 'POST', $options);
 
        $result = json_decode($response['msg'],true);

        // var_dump($result);


        return $result;
        
        


    }
    
    
    public static function Tuikuan($transNo,$price,$price2,$returnUrl){

        $data['method'] = 'POLYMERIZE_REFUND';
        $data['version'] = '1.0';
        $data['format'] = 'JSON';
        $data['merchantNo'] = self::merchantNo;
        $data['signType'] = 'RSA2';
        $data['signContent'] = '';
        $data['sign'] = '';

        $pay_data['transNo'] = 'TK'.$transNo.date('YmdHis');
        $pay_data['origTransNo'] = $transNo;
        $pay_data['payType'] = 'WECHAT_APPLET';
        $pay_data['origOrderAmt'] =  bcmul($price, 100); 
        $pay_data['orderAmt'] = bcmul($price2, 100);
        $pay_data['refundReason'] = '人工客服退款';
        $pay_data['requestDate'] = date('YmdHis');
        $pay_data['returnUrl'] = $returnUrl;

 
        $data['signContent'] = json_encode($pay_data,JSON_UNESCAPED_UNICODE);
        $destDir = ROOT_PATH . 'public'. DS;

        $rsaUtil = new RsaUtil($destDir .'dongbaoyun_pri.pfx',$destDir .'MANDAO_810083647187_pub.cer','123456');

        $signStr = "method=".$data['method']."&version=".$data['version']."&format=".$data['format']."&merchantNo=".$data['merchantNo']."&signType=".$data['signType']."&signContent=".$data['signContent']."&key=".self::privateKey;

        $encrypted = $rsaUtil->sign($signStr);
        $data['sign'] = $encrypted;

        $headers = [];
        $options = [
            CURLOPT_HTTPHEADER => $headers
        ];

     

        $response = Http::sendRequest(self::url, $data, 'POST', $options);
 
        $result = json_decode($response['msg'],true);



        return $result;
    }



    public static function rsa2_sign($data, $privateKey) {
    // 自动格式化私钥为 PEM 格式（如只提供纯Base64内容）
    if (strpos($privateKey, 'BEGIN') === false) {
        $privateKey = chunk_split($privateKey, 64, "\n");
        $privateKey = "-----BEGIN PRIVATE KEY-----\n" . $privateKey . "-----END PRIVATE KEY-----";
    }

    $res = openssl_pkey_get_private($privateKey);
    if (!$res) {
        throw new Exception("无效的私钥格式");
    }

    $result = openssl_sign($data, $signature, $res, OPENSSL_ALGO_SHA256);
    openssl_free_key($res);

    return $result ? base64_encode($signature) : false;
}

}